package com.czmh.etc.onlinepubsys.messagehandler;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.czmh.etc.onlinepubsys.constants.QrCodeConstants;
import com.czmh.etc.onlinepubsys.maper.EtcUserMapper;
import com.czmh.etc.onlinepubsys.model.EtcUser;
import com.czmh.etc.onlinepubsys.services.EtcUserInfoSevice;
import com.czmh.etc.onlinepubsys.services.QrCodePromoterService;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
/**
 * @描述：用户首次关注公众号时推送的事件处理逻辑
 * @author： Seven.
 * @创建日期：2019-11-18 14:28:11
 * @版本：1.0.0
 */
@Slf4j
@Component
public class SubscribeEventMessageHander implements WxMpMessageHandler {
    @Value("${weburl}")
    private String weburl;
    
    @Autowired
    private EtcUserInfoSevice     etcUserInfoSevice;
    @Autowired
    private QrCodePromoterService qrCodePromoterService;
    @Autowired
    private EtcUserMapper         etcUserMapper;
    
	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage message, Map<String, Object> context, WxMpService wxMpService,
			WxSessionManager sessionManager) throws WxErrorException {
		WxMpXmlOutMessage reMsg = null;
		//发送者帐号
		String fromUser=message.getFromUser();
		//开发者微信号
		String touser=message.getToUser();
		// 事件KEY值
		String eventKey = message.getEventKey();
		String lang = "zh_CN"; //语言
		WxMpUser wpMpUser = wxMpService.getUserService().userInfo(fromUser,lang);
		// 初始化保存关注用户的信息，收集记录openid、昵称、头像、地区等信息
		EtcUser etcUser = etcUserInfoSevice.saveWechatInfo(wpMpUser);
		// 如果eventkey有值则表示扫描带参数的二维码但未关注公众号
		if (StringUtils.isNotEmpty(eventKey)) {
			log.info("用户扫描带参数的二维码关注公众号并处理scene参数业务=========="+eventKey);
			String scene = eventKey.split("_")[1];
			if(StringUtils.isNotEmpty(scene) && scene.startsWith(QrCodeConstants.QR_LEVEL_1)){
				// 绑定二级关系，同时增加扫码记录,返回二级推广员二维码图片链接
			    Map<String, String> map = qrCodePromoterService.bindPromoter(etcUser, scene);
				// 回复成为二级的文本消息
			    String msg = "";
			    if (StringUtils.isNotEmpty(map.get("isNew"))) {
			        msg = "您好，欢迎关注“易行易停”！\r\n您已成为手机用户："+ map.get("phone") + "的下级推广员\r\n\r\n" + "<a href=\""+ weburl + "/getQRcode?userId=" + etcUser.getUser_id() +"\">点击获取专属推广码</a>";
                } else {
                    msg = "您好，欢迎关注“易行易停”！\r\n\r\n" + "<a href=\""+ weburl + "/qrcode/getqrcode?userId=" + etcUser.getUser_id() +"\">点击查看您的推广码</a>";
                }
				reMsg = WxMpXmlOutMessage.TEXT()
				        .content(msg)
				        .fromUser(touser)
				        .toUser(fromUser)
				        .build();
			} else {
				// 增加扫码记录
			    qrCodePromoterService.addQrScanRecord(etcUser, scene);
			    String msg = "您好，欢迎关注“易行易停”！\r\n" + 
			            "可以通过易行易停公众号在线填写资料，免费办理ETC。\r\n" + 
			            "马上享受免排队，一卡绑定，畅行全国，出行无忧。\r\n" + 
			            "\r\n" + 
			            "<a href=\"http://wx.formal.caryota.cn\">点击免费办理ETC</a>";
                reMsg = WxMpXmlOutMessage.TEXT()
                        .content(msg)
                        .fromUser(touser)
                        .toUser(fromUser)
                        .build();
			}
		} else {
		    // 用户扫码的不是带参数的场景二维码
            EtcUser update = new EtcUser(etcUser.getUser_id());
            update.setSubscribe(1);
            etcUserMapper.update(update);
            log.info(String.format("[更新用户状态为已关注] 用户id：\"%s\"", etcUser.getUser_id()));
		}
		return reMsg;
	}
}